<template>
  <div class="member-center">
    <!-- 侧边导航栏 -->
    <div class="member-layout">
      <div class="member-sidebar">
        <a-menu :selected-keys="selectedKeys" @menu-item-click="toLink">
          <a-menu-item v-for="item in navList" :key="item.key">
            <template #icon>
              <component :is="item.icon" />
            </template>
            {{ item.label }}
          </a-menu-item>
        </a-menu>
      </div>
      
      <!-- 内容区 -->
      <div class="member-content">
        <!-- VIP检查提示 -->
        <a-modal
          v-model:visible="vipCheckModalVisible"
          title="会员权限检查"
          :width="500"
          :footer="null"
          :mask-closable="true"
          :closable="true"
        >
          <div class="vip-check-modal">
            <div class="vip-check-content">
              <div class="vip-icon">
                <icon-exclamation-circle-fill :size="48" style="color: #ff7d00;" />
              </div>
              <h3>您还不是会员</h3>
              <p>会员功能需要购买会员后才能使用，请先购买会员</p>
              <div class="vip-actions">
                <a-button type="primary" size="large" @click="openPaymentModal">
                  立即购买
                </a-button>
                <a-button size="large" @click="closeVipCheckModal" style="margin-left: 12px;">
                  稍后再说
                </a-button>
              </div>
            </div>
          </div>
        </a-modal>

        <!-- 支付模态框 -->
        <PaymentModal ref="paymentModalRef" @payment-completed="handlePaymentCompleted" />

        <!-- 子路由内容区域 -->
        <div class="content-section">
          <router-view></router-view>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, shallowRef, watchEffect, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRouter, useRoute } from 'vue-router'
import {
  IconUp,
  IconDown,
  IconRight,
  IconClose,
  IconCalendarClock,
  IconSchedule,
  IconExclamationCircleFill,
  IconLock,
  IconUser,
  IconGift,
  IconSettings,
  IconMessage,
  IconHome,
  IconCalendar,
  IconStar,
  IconBook
} from '@arco-design/web-vue/es/icon'
import PaymentModal from '../../components/member/PaymentModal.vue'
import { checkVipRequest } from '../../apis/order-api'
import useUserStore from '../../sotre/user-store'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 检查登录状态
const checkLogin = () => {
  if (!userStore.isLogin) {
    router.push('/login')
  }
}

// 侧边栏相关逻辑
const selectedKeys = ref([])
const navList = shallowRef([])

// 菜单列表
const memberList = [
  { key: '/member/center', label: '会员信息', icon: IconUser },
  { key: '/member/center/benefits', label: '会员权益', icon: IconGift },
  { key: 'function-cards', label: '会员功能', icon: IconSettings },
  { key: '/member/center/weekly-plan-intro', label: '周计划', icon: IconCalendar },
  { key: '/member/center/course-schedule-intro', label: '课表', icon: IconSchedule },
  { key: '/member/center/habit-21-intro', label: '21天习惯', icon: IconStar },
  { key: '/member/center/tutorial', label: '使用教程', icon: IconBook }
]

// 检查导航
const checkNav = () => {
  const currentPath = route.path
  
  // 设置菜单列表
  navList.value = memberList
  
  // 设置选中项（排除function-cards这个特殊菜单项）
  if (currentPath !== 'function-cards') {
    selectedKeys.value = [currentPath]
  }
}

// 路由跳转
const toLink = ({ key }) => {
  console.log('Menu item clicked, key:', key)
  console.log('Current route path:', route.path)
  console.log('Router instance:', router)
  
  // 特殊处理会员功能菜单项
  if (key === 'function-cards') {
    // 显示功能卡片组件
    router.push('/member/center/function-cards')
    return
  }
  
  // 检查是否已经在目标页面
  if (route.path === key) {
    console.log('Already on target page, skipping navigation')
    return
  }
  
  try {
    router.push(key)
    console.log('Navigation successful')
  } catch (error) {
    console.error('Navigation failed:', error)
  }
}

// 响应式数据
const isVip = ref(false)
const vipCheckModalVisible = ref(false) // 初始状态为false，确保模态框不会自动显示
const paymentModalRef = ref(null)

// 检查VIP状态
const checkVipStatus = async () => {
  try {
    const response = await checkVipRequest()
    isVip.value = response.data
    
    // 如果不是VIP，不自动显示提示模态框，让用户自行探索
    // 只有在点击VIP功能时才提示
    console.log('VIP status checked:', isVip.value)
  } catch (error) {
    console.error('检查VIP状态失败:', error)
    Message.error('检查会员状态失败，请稍后重试')
  }
}

// 打开支付模态框
const openPaymentModal = () => {
  console.log('Opening payment modal')
  vipCheckModalVisible.value = false
  if (paymentModalRef.value) {
    paymentModalRef.value.open()
  }
}

// 关闭VIP检查模态框
const closeVipCheckModal = () => {
  console.log('Closing VIP check modal')
  vipCheckModalVisible.value = false
}

// 处理支付完成
const handlePaymentCompleted = () => {
  // 支付完成后，可以重新检查VIP状态
  // 但由于客服需要审核，这里暂时不自动更新状态
  Message.success('支付完成！客服将在24小时内审核您的订单')
}

// 组件挂载时检查VIP状态
onMounted(() => {
  // 临时设置登录状态用于测试
  if (!userStore.isLogin) {
    userStore.token = 'Bearer mock-token-for-testing'
    userStore.userInfo = {
      id: 1,
      username: 'testuser',
      nickname: '测试用户',
      picture: ''
    }
  }
  
  checkLogin()
  checkNav()
  checkVipStatus()
})

// 监听路由变化
watchEffect(() => {
  checkNav()
})
</script>

<style lang="less" scoped>
.member-center {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--color-bg-1);
  padding-top: 80px; /* 添加上边距，避免被顶栏遮挡 */
  position: relative; /* 确保定位正确 */
  z-index: 1; /* 提高基础层级，确保可点击 */
}

.member-layout {
  display: flex;
  height: 100%;
  position: relative;
  z-index: 0; /* 设置布局层级 */
}

.member-sidebar {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid var(--color-border-2);
  padding: 20px 0;
  flex-shrink: 0;
  z-index: 1; /* 确保侧边栏在正确的层级 */
  pointer-events: auto; /* 确保侧边栏可以接收点击事件 */
}

.member-sidebar :deep(.arco-menu) {
  pointer-events: auto !important; /* 确保菜单可以接收点击事件 */
}

.member-sidebar :deep(.arco-menu-item) {
  pointer-events: auto !important; /* 确保菜单项可以接收点击事件 */
  cursor: pointer !important; /* 确保鼠标指针显示为可点击 */
}

.member-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  position: relative;
  z-index: 0; /* 设置内容区域层级 */
  pointer-events: auto; /* 确保点击事件可以被触发 */
}

.function-cards-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1; /* 确保功能卡片区域在正确的层级 */
  pointer-events: auto; /* 确保点击事件可以被触发 */
  
  &.collapsed {
    margin-bottom: 8px;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border-2);
    
    h2 {
      margin: 0;
      color: var(--color-text-1);
      font-size: 18px;
      font-weight: 600;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 12px;
    }
    
    .collapse-btn {
      color: var(--color-text-3);
      cursor: pointer;
      padding: 4px 8px;
      border-radius: 4px;
      transition: all 0.2s ease;
      
      &:hover {
        color: var(--color-primary);
        background-color: var(--color-primary-light-1);
      }
    }
  }

  .cards-container {
    padding: 20px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
  }

  .function-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid var(--color-border-2);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
  position: relative;
  z-index: 1; /* 确保卡片在正确的层级 */
  pointer-events: auto; /* 确保点击事件可以被触发 */
  
  &:hover {
    border-color: var(--color-primary);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
  
  &.active {
    border-color: var(--color-primary);
    box-shadow: 0 0 0 2px rgba(var(--primary-6), 0.2);
    background: var(--color-primary-light-1);
  }

    .card-icon {
      flex-shrink: 0;
      width: 48px;
      height: 48px;
      border-radius: 8px;
      background: var(--color-primary-light-4);
      display: flex;
      align-items: center;
      justify-content: center;
      color: var(--color-primary);
      margin-right: 12px;
    }

    .card-content {
      flex: 1;
      
      h3 {
        margin: 0 0 4px 0;
        font-size: 16px;
        font-weight: 600;
        color: var(--color-text-1);
      }
      
      p {
        margin: 0;
        font-size: 14px;
        color: var(--color-text-3);
        line-height: 1.4;
      }
      
      .vip-badge {
        margin-top: 8px;
      }
    }

    .card-arrow {
      flex-shrink: 0;
      color: var(--color-text-4);
      margin-left: 8px;
    }
  }
}

.content-section {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  min-height: 400px;
  position: relative;
  z-index: 1; /* 确保内容区域在正确的层级 */
  pointer-events: auto; /* 确保点击事件可以被触发 */
  
  .empty-state {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .content-display {
    height: 100%;
    display: flex;
    flex-direction: column;

    .content-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid var(--color-border-2);
      
      h2 {
        margin: 0;
        color: var(--color-text-1);
        font-size: 18px;
        font-weight: 600;
      }
      
      .close-btn {
        color: var(--color-text-3);
        
        &:hover {
          color: var(--color-primary);
        }
      }
    }

    .content-body {
      flex: 1;
      overflow: hidden;
      
      .content-iframe {
        width: 100%;
        height: 100%;
        border: none;
        min-height: 500px;
      }
      
      .custom-content {
        padding: 20px;
        height: 100%;
        overflow-y: auto;
      }
    }
  }
}

// 自定义内容样式
:deep(.progress-dashboard) {
  .progress-items {
    margin-top: 20px;
  }
  
  .progress-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    gap: 12px;
    
    .progress-bar {
      flex: 1;
      height: 8px;
      background: var(--color-fill-3);
      border-radius: 4px;
      overflow: hidden;
      
      .progress-fill {
        height: 100%;
        background: var(--color-primary);
        transition: width 0.3s ease;
      }
    }
  }
}

:deep(.notes-manager) {
  .notes-list {
    margin-top: 20px;
  }
  
  .note-item {
    padding: 16px;
    border: 1px solid var(--color-border-2);
    border-radius: 8px;
    margin-bottom: 12px;
    
    h4 {
      margin: 0 0 8px 0;
      color: var(--color-text-1);
    }
    
    p {
      margin: 0 0 8px 0;
      color: var(--color-text-3);
      font-size: 14px;
    }
    
    .note-date {
      font-size: 12px;
      color: var(--color-text-4);
    }
  }
}

:deep(.achievements-display) {
  .badges-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
    margin-top: 20px;
  }
  
  .badge-item {
    text-align: center;
    padding: 20px;
    border: 2px solid var(--color-border-2);
    border-radius: 12px;
    transition: all 0.2s ease;
    
    &.earned {
      border-color: var(--color-primary);
      background: var(--color-primary-light-1);
    }
    
    .badge-icon {
      font-size: 32px;
      margin-bottom: 12px;
    }
    
    h4 {
      margin: 0 0 8px 0;
      color: var(--color-text-1);
    }
    
    p {
      margin: 0;
      font-size: 14px;
      color: var(--color-text-3);
    }
  }
}

:deep(.messages-center) {
  .message-tabs {
    display: flex;
    border-bottom: 1px solid var(--color-border-2);
    margin-bottom: 20px;
    
    .tab {
      padding: 12px 20px;
      cursor: pointer;
      color: var(--color-text-3);
      border-bottom: 2px solid transparent;
      
      &.active {
        color: var(--color-primary);
        border-bottom-color: var(--color-primary);
      }
    }
  }
  
  .messages-list {
    .message-item {
      display: flex;
      align-items: flex-start;
      padding: 16px 0;
      border-bottom: 1px solid var(--color-border-2);
      
      &.unread .message-dot {
        width: 8px;
        height: 8px;
        background: var(--color-primary);
        border-radius: 50%;
        margin-right: 12px;
        margin-top: 6px;
        flex-shrink: 0;
      }
      
      .message-content {
        flex: 1;
        
        h4 {
          margin: 0 0 4px 0;
          color: var(--color-text-1);
        }
        
        p {
          margin: 0 0 8px 0;
          color: var(--color-text-3);
          font-size: 14px;
        }
        
        .message-time {
          font-size: 12px;
          color: var(--color-text-4);
        }
      }
    }
  }
}

:deep(.rewards-mall) {
  .points-info {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px;
    background: var(--color-primary-light-1);
    border-radius: 8px;
    
    h3 {
      margin: 0;
      color: var(--color-text-1);
      
      .points-value {
        color: var(--color-primary);
        font-weight: bold;
      }
    }
  }
  
  .rewards-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .reward-item {
    text-align: center;
    padding: 20px;
    border: 1px solid var(--color-border-2);
    border-radius: 8px;
    
    .reward-image {
      font-size: 48px;
      margin-bottom: 12px;
    }
    
    h4 {
      margin: 0 0 8px 0;
      color: var(--color-text-1);
    }
    
    .reward-points {
      margin: 0 0 16px 0;
      color: var(--color-primary);
      font-weight: bold;
    }
    
    .redeem-btn {
      padding: 8px 16px;
      background: var(--color-primary);
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      
      &:hover {
        background: var(--color-primary-dark-1);
      }
    }
  }
}

:deep(.settings-panel) {
  .settings-sections {
    margin-top: 20px;
  }
  
  .setting-section {
    margin-bottom: 24px;
    
    h4 {
      margin: 0 0 12px 0;
      color: var(--color-text-1);
      font-size: 16px;
    }
  }
  
  .setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--color-border-2);
    
    &:last-child {
      border-bottom: none;
    }
    
    label {
      color: var(--color-text-2);
    }
  }
}

// VIP检查模态框样式
.vip-check-modal {
  .vip-check-content {
    text-align: center;
    padding: 20px;
    
    .vip-icon {
      margin-bottom: 16px;
    }
    
    h3 {
      margin-bottom: 12px;
      color: var(--color-text-1);
      font-size: 18px;
    }
    
    p {
      margin-bottom: 24px;
      color: var(--color-text-2);
      line-height: 1.6;
    }
    
    .vip-actions {
      display: flex;
      justify-content: center;
      gap: 12px;
    }
  }
}

// VIP限制内容样式
.vip-restricted {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 300px;
  
  .restricted-content {
    text-align: center;
    
    h3 {
      margin-bottom: 12px;
      color: var(--color-text-1);
      font-size: 18px;
    }
    
    p {
      margin-bottom: 24px;
      color: var(--color-text-2);
      line-height: 1.6;
    }
  }
}
</style>